local cjson = require "cjson.safe"

function replace_text(data)
    if type(data) == "string" then
        -- 替换字符串中的“周杰伦”为“JAY”
        return data:gsub("周杰伦", "JAY")
    elseif type(data) == "table" then
        for k, v in pairs(data) do
            data[k] = replace_text(v) -- 递归替换
        end
    end
    return data
end

function main()
    local chunk, eof = ngx.arg[1], ngx.arg[2]
    local buffered = ngx.ctx.buffered
    if not buffered then
        buffered = {}
        ngx.ctx.buffered = buffered
    end
    if chunk ~= "" then
        buffered[#buffered + 1] = chunk
    end
    if eof then
        local response = table.concat(buffered)
        local data = cjson.decode(response)
        if data then
            data = replace_text(data) -- 替换文本
            response = cjson.encode(data)
        end
        ngx.arg[1] = response
    else
        ngx.arg[1] = nil
    end
end

main()
